package com.study.io.nio.demo.channel;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;

/**
 * DatagramChannel
 *
 * @author wuxj
 */
public class DatagramChannelDemo {

    public static void start(int port) {
        // 打开DatagramChannel，监听UDP9999端口
        try (DatagramChannel channel = DatagramChannel.open()) {
            channel.socket().bind(new InetSocketAddress(port));
            ByteBuffer buffer = ByteBuffer.allocate(100);
            // 通过channel的recevice方法接收UDP数据包
            channel.receive(buffer);
            buffer.flip();
            printBuffer(buffer);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void printBuffer(ByteBuffer buffer) {
        Charset charset = Charset.forName("UTF-8");
        CharsetDecoder decoder = charset.newDecoder();
        try {
            CharBuffer buf = decoder.decode(buffer);
            buffer.flip();
            System.out.println(buf.toString());
        } catch (CharacterCodingException e) {
            e.printStackTrace();
        }
    }
}
